package com.pocket.insight.base.sql.resultProcessor;

import com.pocket.insight.controller.dto.DatasetResultDto;
import com.pocket.insight.entity.Dataset;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 *
 * @author shuize
 * @create 2024/11/30
 */
public class BaseWriteResultSetProcessor implements WriteResultSetProcessor {

    protected Map<String, Dataset.Field> schemaMap;
    protected DatasetResultDto           datasetResultDto;
    private   Long                       limit;

    public BaseWriteResultSetProcessor() {
        this.datasetResultDto = new DatasetResultDto();
        this.datasetResultDto.setData(new ArrayList());
        this.datasetResultDto.setSchema(new ArrayList());
        this.datasetResultDto.setMapData(new ArrayList());
    }

    @Override
    public void initMetaFields(List<Dataset.Field> fields) throws SQLException {
        this.datasetResultDto.setSchema(fields);
        if (this.schemaMap != null) {
            fields.forEach(field -> {
                Dataset.Field tempField = this.schemaMap.get(field.getFieldName());
                if (tempField == null) {
                    return;
                }
                String fieldName = tempField.getFieldName();
                String label = tempField.getLabel();
                String oriLabel = tempField.getOriginLabel();
                String realLabel = (label == null) ? ((oriLabel == null) ? fieldName : oriLabel) : label;
                field.setLabel(realLabel);
                field.setComment(tempField.getComment());
                field.setUserComment(tempField.getUserComment());
                field.getGeneratedOptions().setOriginName(tempField.getOriginName());
            });
        }
    }

    @Override
    public boolean processOneRow(List<Object> row) throws IOException {
        this.datasetResultDto.fetchData().add(row);
        return true;
    }

    @Override
    public void cleanup() {

    }

    public DatasetResultDto getDatasetResultDto() {
        DatasetResultDto r = this.datasetResultDto;
        reset();
        return r;
    }

    public void reset() {
        this.datasetResultDto = new DatasetResultDto();
        this.datasetResultDto.setData(new ArrayList());
        this.datasetResultDto.setSchema(new ArrayList());
        this.datasetResultDto.setMapData(new ArrayList());
    }
}
